package com.turntochild.sxcb;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.eternity.classes.ATRP;
import com.eternity.classes.ATRP.Callback;
import com.innofidei.tools.InnofideiTools;
import com.turntochild.sxcb.ITurnToChildAppService.Stub;
import com.wondertek.mist.MistActivity;
import com.wondertek.mist.Utils;
import com.wondertek.mist.utils.StringUtils;




public class TurnToChildService extends Service {



	private static final int CHECK_START=0;
	private static final int CHECK_ERROR=1;
	private static final int CHECK_FAILURE=2;
	private static final int CHECK_SUCCESS=3;
	


	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CHECK_SUCCESS:
				
				Toast.makeText(TurnToChildService.this,"验证成功", Toast.LENGTH_SHORT).show();
//				Utils.sendMamLog(TurnToChildService.this, "true");
				toMistActivity((JSONObject)msg.obj);
				break;

			case CHECK_START:
				Toast.makeText(TurnToChildService.this,"请稍等，正在验证数据...", Toast.LENGTH_SHORT).show();
				break;
			case CHECK_ERROR:
				Toast.makeText(TurnToChildService.this,"连接服务器失败", Toast.LENGTH_SHORT).show();
				break;
				

			case CHECK_FAILURE:
				JSONObject error=(JSONObject)msg.obj;
				
				try {
					Toast.makeText(TurnToChildService.this,error==null?"数据异常":error.getString("error"), Toast.LENGTH_SHORT).show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
//				Utils.sendMamLog(TurnToChildService.this, "false");
				break;


			default:
				break;
			}
		};
	};

	

	

	@Override
	public IBinder onBind(Intent arg0) {
		return new TurnToChildBinder();
	}


	@Override
	public void onCreate() {
		super.onCreate();		
	}

	/**
	 * MAM调用方法，然后跳转界面
	 */
	public class TurnToChildBinder extends Stub{

		public void turnToChildApps(String encryptCode) throws RemoteException {
			checkIsSuccess(encryptCode);
		}

	}

	/**
	 * 将协议解析成Json类型字符串
	 */
	public void checkIsSuccess(final String encryptCode) {
		
		try {
			String codeString = InnofideiTools.decrypt(encryptCode,"CpicAppstore");
			JSONTokener jsonParser = new JSONTokener(codeString);
			final JSONObject param = ((JSONObject) jsonParser.nextValue()).getJSONObject("params");
			param.put("sxUserId", param.getString("userid"));
			//Log.i("MAM",param.toString());
           
			
            String checkUrl = Utils.getMetaValue(this, "mam.checkUrl");
            
            if(StringUtils.isBlank(checkUrl)){
            	
            	Utils.saveString(TurnToChildService.this, "mam.encryptCode", encryptCode);  
            	toMistActivity(param);
            }else{
            	ATRP.request(checkUrl,null ,param,new Callback() {
                    
        			public void onStart() {
        				Message message = new Message();
        				message.what = CHECK_START;	
        				handler.sendMessage(message);
        				
        			}

        			public void onFailure(String msg) {
        				Message message = new Message();
        				message.what = CHECK_ERROR;
        				handler.sendMessage(message);
        			}

        			@Override
        			public void onSuccess(JSONObject result, Header[] headers) {
        				
        				boolean success=false;
        				if (result == null) {
        					success=false;
        				}else{
        					try {
    							success=result.getBoolean("success");
    						} catch (JSONException e) {
    						}
        				}
        				if(success){
        					Utils.saveString(TurnToChildService.this, "mam.encryptCode", encryptCode);   					
        					Message message = new Message();
        					message.what = CHECK_SUCCESS;
        					try {
								param.put("zhiCorpCode", result.getString("zhiCorpCode"));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
        					message.obj = param;
        					handler.sendMessage(message);
        				}else{
        					Message message = new Message();
        					message.what = CHECK_FAILURE;
        					//Log.i("result", result.toString());
        					message.obj = result;
        					handler.sendMessage(message);
        				}
        				
        				
        				
        			}
        		
        		});
            }
    		
    		
		} catch (Exception e) {
			e.printStackTrace();

		}
	}




	/**
	 * 调用activity
	 */
	private void toMistActivity(JSONObject param) {

		
		Intent intent = new Intent();
		intent.setAction(Utils.ACTION_MAM);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(this, MistActivity.class);
		intent.putExtra("param", param.toString());
		//Log.i("param", param.toString());
		
		Utils.saveString(this.getApplicationContext(), "param", param.toString());
		
		this.startActivity(intent);
	}

}

